package com.itheima03;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

@SuppressWarnings("all")
public class DemoJdbc {
    //使用事务完成转账案例
    public static void main(String[] args) {
        Connection con = null;
        Statement sta = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db10", "root", "root");
            //开启事物
            con.setAutoCommit(false);

            sta = con.createStatement();
            String sql1 = "update account set money=money+1000 where name='jack';";
            //int a = 10 / 0;
            String sql2 = "update account set money=money-1000 where name='rose';";
            int row1 = sta.executeUpdate(sql1);
            int row2 = sta.executeUpdate(sql2);
            if (row1 > 0 && row2 > 0) {
                System.out.println("转账成功");
                con.commit();
            }
        } catch (Exception e) {
            System.out.println("转账失败" + e.toString());
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            if (sta != null) {
                try {
                    sta.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
